from django.conf import settings
from django.utils.encoding import smart_str
from django.template.loader import get_template
from django.template import Context
from django.contrib.auth.models import User, Group

'''
TO DO:
 Set the logo: [header_logo] src and link
 Give users admin access to the Trac admin pages:  trac-admin <path> permissions add <username> TRAC_ADMIN
 [mainnav]
 Deal with changes to the slug, and auto-generate the slug in the admin
'''


def sync_repository_ini(repo):
    try:
	global_ini_path = settings.TRAC_INI_PATH
    except:
	global_ini_path = '/etc/trac/trac.ini'
    template = get_template('tracadmin/trac.ini')
    ini_path = settings.TRAC_PATH_BASE + smart_str(repo.slug) + '/conf/trac.ini'
    # XXX there's a race condition here
    ini_file = open(ini_path,'w')
    context = Context({'repository':repo,
		       'trac_ini_path':global_ini_path})
    ini_file.write( template.render(context) )
    ini_file.close()


def save_repository(repo):
    slug = smart_str(repo.slug)
    title = smart_str(repo.title)
    # XXX should sanitize the title better here
    trac_path = settings.TRAC_PATH_BASE + slug
    svn_path = settings.SVN_PATH_BASE + slug
    import os
    if not os.path.exists(svn_path):
        os.system('svnadmin create "%s"' % svn_path)
    if not os.path.exists(trac_path):
        os.system('trac-admin "%s" initenv "%s" sqlite:db/trac.db svn "%s"' % (trac_path, title, svn_path))
    sync_repository_ini(repo)


def delete_repository(repo):
    slug = smart_str(repo.slug)
    import os
    os.system('rm -rf "%s%s" "%s%s"' % (settings.SVN_PATH_BASE, slug, settings.TRAC_PATH_BASE, slug))


def sync_svn_access_file(perms):
    template = get_template('tracadmin/svn-access-file')
    # XXX Another race condition here!
    svn_access_file = open('/etc/subversion/svn-access-file', 'w')
    context = Context({'perms':perms,
                       'users':User.objects.all(),
                       'groups':Group.objects.all()})
    svn_access_file.write( template.render(context) )
    svn_access_file.close()
